<template>
  <view class="condition-box">
    <view class="item-box">
      <view
        class="item"
        v-for="(option, index) in integratedOptions"
        :key="index"
        :class="{ checked: isChecked(option) }"
        @click="onClick(option)"
      >
        {{ getShowLabel(option) }}
      </view>
    </view>
  </view>
  <check-box-selector
    :top="selectorTop"
    height="600rpx"
    @confirm="selector.confirmHandle"
    v-model:call-out="selector.isCallOut"
    :questionnaire="selector.questionnaire"
  >
  </check-box-selector>
</template>

<script setup lang="ts">
import checkBoxSelector from './check-box-selector/index.vue'
import { onMounted, ref, watch } from 'vue'
import type { SurveyItem, Result, Option, MixinSurveyItem } from './check-box-selector/type'
import deepClone from './utils/deep-clone'
let props = defineProps({
  options: {
    type: Array<SurveyItem>, //接受的数据类型
    default: [] //接受默认数据
  },
  mixinOptions: {
    type: Array<MixinSurveyItem>,
    default: [] //接受默认混入数据
  },
  selectorTop: {
    type: String,
    default: '0px'
  }
})
let emits = defineEmits<{
  (e: 'change', submitData: Result[]): void
  (e: 'callOut', isCallOut: boolean): void
  (e: 'ready'): void
}>()
// 拷贝一份，不污染原来的,命名为integratedOptions
const integratedOptions = ref<SurveyItem[]>(deepClone(props.options))
onMounted(() => {
  // 混入-根据SurveyItem的name
  props.mixinOptions.forEach((mixinOption) => {
    const surveyItem = integratedOptions.value.find((item) => item.name === mixinOption.name)
    if (surveyItem == null) return
    Object.assign(surveyItem, mixinOption)
  })
  // 触发已可搜索筛选参数状态：ready状态
  emits('ready')
})

// 判断是否已经选中
function isChecked(surveyItem: SurveyItem): boolean {
  const surveyValue = surveyItem.value
  return !(surveyValue === false || surveyValue === null || (Array.isArray(surveyValue) && surveyValue.length === 0))
}
// submitData
function getSubmitData(): Result[] {
  const results: Result[] = []
  integratedOptions.value.forEach((surveyItem: SurveyItem) => {
    if (!isChecked(surveyItem)) return
    results.push({
      name: surveyItem.name,
      value: surveyItem.value
    })
  })
  return results
}
// 根据value找到选项
function getCheckedOption(surveyItem: SurveyItem): Option[] | null {
  if (surveyItem.options == null || !Array.isArray(surveyItem.options) || surveyItem.value == null) return null
  const surveyItemValue = (Array.isArray(surveyItem.value) ? surveyItem.value : [surveyItem.value]) as Array<
    number | string
  >
  return surveyItem.options.filter((option) => surveyItemValue.includes(option.value))
}
// 获取显示的label
function getShowLabel(option: SurveyItem) {
  // 当未选中时
  if (!isChecked(option)) return option.label
  // 当选中时
  const checkedOptions = getCheckedOption(option)
  if (checkedOptions == null || checkedOptions.length > 1) return option.label
  return checkedOptions[0].label
}
// 滚动选择
const scrollSelection = (surveyItem: SurveyItem) => {
  if (surveyItem.options == null || surveyItem.options.length === 0 || surveyItem.isMultipleChoice) return
  // 可以进行滚动
  if (surveyItem.value == null) {
    surveyItem.value = surveyItem.options[0].value
    return
  }
  for (let i = 0; i < surveyItem.options.length; i++) {
    const option = surveyItem.options[i]
    if (option.value === surveyItem.value && i + 1 < surveyItem.options.length) {
      surveyItem.value = surveyItem.options[i + 1].value
      return
    }
  }
  return (surveyItem.value = null)
}
async function onClick(surveyItem: SurveyItem) {
  // 看要不要初始化值，如果没值
  const isNeedInit =
    surveyItem.options == null ||
    surveyItem.options.length === 0 ||
    (surveyItem?.isInitialized === false && (surveyItem.isInitialized = true))

  if (isNeedInit && surveyItem.initOptions != null) {
    surveyItem.options = await surveyItem.initOptions!()
  }
  if (surveyItem.isMultipleChoice === undefined && surveyItem.options === undefined) {
    // 直接改变状态
    surveyItem.value = !surveyItem.value
    return
  }
  // 如果是单选且选项个数只有2个，那使用滚动的方式
  if (surveyItem.isMultipleChoice === false && surveyItem.options?.length === 2) {
    // 滚动的方式
    scrollSelection(surveyItem)
    // 触发确认事件-将会刷新店铺信息
    selector.value.confirmHandle()
    return
  }
  // 调起让用户选择
  selector.value.callOut(surveyItem)
}

const selector = ref({
  isCallOut: false,
  questionnaire: [] as SurveyItem[],
  confirmHandle() {
    emits('change', getSubmitData())
  },
  callOut(surveyItem: SurveyItem) {
    selector.value.isCallOut = true
    selector.value.questionnaire = [surveyItem]
  }
})
watch(
  () => selector.value.isCallOut,
  (newVal) => {
    emits('callOut', newVal)
  }
)

defineExpose({
  getSubmitData,
  isCallOut: selector.value.isCallOut
})
</script>

<style scoped lang="scss">
@use 'sass:math';

$view-max-weight: 750rpx;
$condition-item-left-margin-size: 25rpx;
$check-box-item-width: math.div($view-max-weight - $condition-item-left-margin-size * 5, 4);

.condition-box::-webkit-scrollbar {
  display: none; /* Chrome Safari */
}

.condition-box {
  overflow: scroll;
  width: $view-max-weight;
  height: 45px;
  background-color: #f5f5f5;
  box-sizing: border-box;

  .item-box {
    display: inline-flex;
    align-items: center;
    height: 100%;

    /* 实现x轴实现的重要css */
    white-space: nowrap;

    .checked {
      background-color: #ffd350 !important;
    }

    > .item:last-child {
      margin-right: $condition-item-left-margin-size;
    }

    > .item {
      display: inline-block;
      margin-left: $condition-item-left-margin-size;
      padding: 0 2px;

      // 本来是$condition-item-left-margin-size * 8 但出现边距合并，只有5个有效的边距宽度
      min-width: $check-box-item-width;
      max-width: $check-box-item-width;
      height: 30px;
      font-size: 23rpx;
      text-align: center;
      background-color: #fff;
      line-height: 30px;
      box-sizing: border-box;
      text-wrap: nowrap;
    }
  }
}
</style>
